package cn.skylark.wcm.common.scheduler;

import cn.skylark.wcm.common.jwt.JwtUtil;
import cn.skylark.wcm.common.redis.RedisUtils;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Iterator;
import java.util.Set;

@Component
public class ScheduledJob2 implements Job {
    @Autowired
    RedisUtils redisUtils;
    /** logger */
    private static final Logger LOGGER = LoggerFactory.getLogger(ScheduledJob2.class);
    /**
     * 定时任务(REDIS服务器过期TOKEN清理处理)
     * 业务:
     * 1:获取REDIS服务器上所有TOKEN的KEY值
     * 2:遍历KEY值,分别取出每个TOKEN的过期时间
     * 3:过期时间与系统当前时间进行比较,超过当前时间的TOKEN内容从REDIS服务器上清除
     *
     * @param arg0
     * @throws JobExecutionException
     */
    @Override
    public void execute(JobExecutionContext arg0) throws JobExecutionException {
        LOGGER.info( "REDIS服务器过期TOKEN清理处理---开始！" );
        Set<String> set = redisUtils.redisTemplate.keys( "token|*" );
        Iterator<String> it=set.iterator() ;
        while(it.hasNext()){
            String key = it.next();
            String redisToken = (String) redisUtils.get( key);
            if (redisToken != null) {
                try {
                    //获取TOKEN过期时间
                    Date expiration = Jwts.parser()
                            .setSigningKey( JwtUtil.SECRET )
                            .parseClaimsJws( redisToken.replace( JwtUtil.TOKEN_PREFIX, "" ) )
                            .getBody().getExpiration();
                    //比较TOKEN过期时间与当前时间
                    if (expiration.before( new Date( System.currentTimeMillis() ) )) {
                        redisUtils.remove( key );
                        LOGGER.info( "REDIS服务器过期TOKEN清理处理---KEY=" + key );
                    }
                }catch (JwtException e){
                    redisUtils.remove( key );
                    LOGGER.info( "REDIS服务器过期TOKEN清理处理---KEY=" + key );
                }
            }
        }
        LOGGER.info("REDIS服务器过期TOKEN清理处理---结束！" );
    }

}
